package com.he.utils;

import com.he.domain.Result;
import com.he.enums.LoginStatusEnum;
import com.he.enums.StatusCodeEnum;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.AuthorizationServiceException;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.server.csrf.CsrfException;

/**
 * @author He
 * @version 1.0
 * @Date 2023/9/7 9:14
 * @Desc 认证异常统一封装
 */
public class AuthExceptionUtil {
    public static Result getAuthExceptionType(AuthenticationException authException) {
        authException.printStackTrace();
        Result<?> result;
        if(authException instanceof BadCredentialsException){
            return Result.fail(LoginStatusEnum.INVALID_CREDENTIALS);
        } else if (authException instanceof InsufficientAuthenticationException) {
            return Result.fail(LoginStatusEnum.UNAUTHORIZED);
        }else if (authException instanceof InternalAuthenticationServiceException){
            return Result.fail(LoginStatusEnum.USER_NOT_REGISTERED);
        }else if(authException instanceof LockedException){
            return Result.fail(LoginStatusEnum.USER_LOCKED);
        }else if(authException instanceof AccountExpiredException){
            return Result.fail(LoginStatusEnum.ACCOUNT_EXPIRED);
        }else if(authException instanceof DisabledException){
            return Result.fail(LoginStatusEnum.DISABLED);
        }else if(authException instanceof AuthenticationServiceException){
            return Result.fail(LoginStatusEnum.AUTHORIZATION_FAILURE);
        } else if (authException instanceof InsufficientAuthenticationException) {
            return Result.fail(LoginStatusEnum.NO_OPERATOR_AUTH);
        }
        return Result.fail(StatusCodeEnum.SYSTEM_ERROR.getCode(), authException.getMessage());
    }

    public static Result getAccessExceptionType(AccessDeniedException e) {
        if (e instanceof CsrfException) {
            return Result.fail(-1001, "非法访问跨域请求异常!");
        } else if (e instanceof org.springframework.security.web.csrf.CsrfException) {
            return Result.fail(-1002,"非法访问跨域请求异常!");
        } else if (e instanceof AuthorizationServiceException) {
            return Result.fail(LoginStatusEnum.AUTHORIZATION_FAILURE);
        }else if (e instanceof AccessDeniedException) {
            return Result.fail(LoginStatusEnum.NO_OPERATOR_AUTH);
        }
        return Result.fail(StatusCodeEnum.SYSTEM_ERROR.getCode(), e.getMessage());
    }
}
